package com.ghpt.controller;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.ghpt.dto.JiaoTongXQUpdateDTO;
import com.ghpt.dto.JiaotongDailyAvgDTO;
import com.ghpt.pojo.JiaoTongXQ;

import com.ghpt.pojo.SolarRadiation;
import com.ghpt.service.JiaoTongXQService;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/jiaotongxq")
public class JiaoTongXQController {
    private final JiaoTongXQService jiaoTongXQService;

    public JiaoTongXQController(JiaoTongXQService jiaoTongXQService) {
        this.jiaoTongXQService = jiaoTongXQService;
    }
    @GetMapping("/{id}")
    public JiaoTongXQ getJiaoTongXQById(@PathVariable Long id) {
        System.out.println("结果是"+jiaoTongXQService.findJiaoTongXQById(id));
        return jiaoTongXQService.findJiaoTongXQById(id);
    }
    @PutMapping
    public int updateJiaoTongXQ(@RequestBody JiaoTongXQ jiaoTongXQ) {
        return jiaoTongXQService.updateById(jiaoTongXQ);
    }
    @GetMapping("/all")
    public List<JiaoTongXQ> getAllJiaoTongXQ() {
        List<JiaoTongXQ> list = new ArrayList<>();
        for (long i = 1; i <= 96; i++) {
            list.add(jiaoTongXQService.findJiaoTongXQById(i));
        }
        return list;
    }
    /**
     * 获取指定日期范围的太阳辐射数据（分页查询）
     * @param page 当前页码
     * @param size 每页大小（建议24）
     * @return 分页数据
     */
    @GetMapping("/page")
    public IPage<JiaoTongXQ> getJiaoTongXQByPage(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "24") int size) {
        Page<JiaoTongXQ> pageParam = new Page<>(page, size);
        // 只查询id从97开始的数据
        return jiaoTongXQService.findJiaoTongXQByPage(pageParam);
    }

    /**
     * 获取所有天数的平均太阳辐射数据
     * @return 365天的平均值列表
     */
    @GetMapping("/daily-average")
    public List<JiaotongDailyAvgDTO> getDailyAverageJiaoTongXQ(@RequestParam Integer years) {
        return jiaoTongXQService.calculateDailyAverage(years);
    }
    @PutMapping("single/{id}")
    public int updateValueById(@PathVariable Long id, @RequestBody JiaoTongXQUpdateDTO dto) {
        return jiaoTongXQService.updateValue(id, dto.getValue());
    }

    @PostMapping("/upload/{startId}")
    public ResponseEntity<?> upload(@RequestParam("file") MultipartFile file,
                                    @PathVariable("startId") Long startId) {
        if (file.isEmpty()) {
            return ResponseEntity.badRequest().body(Map.of("message", "文件为空"));
        }

        List<JiaoTongXQ> dataList = new ArrayList<>();

        try (Reader reader = new InputStreamReader(file.getInputStream());
             CSVParser csvParser = CSVFormat.DEFAULT.parse(reader)) {

            int count = 0;
            for (CSVRecord record : csvParser) {
                JiaoTongXQ entity = new JiaoTongXQ();
                entity.setId(startId + count); // 自动设置 ID 范围
                entity.setValue(Double.parseDouble(record.get(0).trim()));
                dataList.add(entity);
                count++;
            }

            if (count != 24) {
                return ResponseEntity.badRequest()
                        .body(Map.of("message", "数据条数不为24条！"));
            }

            jiaoTongXQService.replaceRows(startId, startId + 23, dataList);
            return ResponseEntity.ok(Map.of("message", "数据导入成功！"));

        } catch (IOException | NumberFormatException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Map.of("message", "文件解析失败或格式错误"));
        }
    }
}
